package com.situ.object.controll;

import com.situ.object.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
*过滤器
* 执行时机，进入要访问的页面之前
* */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //放行
        //获取访问的url
        String url = request.getRequestURI();

        //放行的请求
        if (url.endsWith(".jsg")
                || url.endsWith(".jpg")
                || url.endsWith(".js")
                || url.endsWith(".css")
                || url.endsWith("login.jsp")
                || url.endsWith("vercode")
                || url.endsWith("login")
        ){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //登录
        User user =  (User) request.getSession().getAttribute("user");
        //判断登录状态
        if (user != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //没有登录跳转
            response.sendRedirect(request.getContextPath()+ "/login.jsp");
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy...");
    }
}
